package com.syezon.wifikey.wifi;

import android.animation.ValueAnimator;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.syezon.wifikey.R;
import com.syezon.wifikey.utils.Utils;
import com.syezon.wifikey.utils.WifiUtil;
import com.syezon.wifikey.wifi.dialog.EnterPwdDialog;
import com.syezon.wifikey.wifi.info.WifiInfo;
import com.syezon.wifikey.wifi.receiver.SimpleConnectChangeObserver;
import com.syezon.wifikey.wifi.receiver.WiFiConnectReceiver;

import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import pl.droidsonroids.gif.GifImageView;

public class WiFiConnectDialog extends Dialog implements ConnectCallBack {

    private static final String TAG = WiFiConnectDialog.class.getSimpleName();

    @BindView(R.id.gifIv)
    GifImageView mGifIv;
    @BindView(R.id.pb_progress)
    ProgressBar mPbProgress;
    @BindView(R.id.tv_ssid)
    TextView mTvSsid;
    @BindView(R.id.iv_init)
    ImageView mIvInit;
    @BindView(R.id.iv_check)
    ImageView mIvCheck;
    @BindView(R.id.iv_connect)
    ImageView mIvConnect;

    private static final long MAX_CONNECT_TIME = 20000;
    private Handler mHandler = new Handler();
    private ConnectObserver connectObserver = new ConnectObserver();
    private Runnable mFailConnectTask = new Runnable() {
        @Override
        public void run() {
            onFial(mWifiInfo);
        }
    };
    private WifiInfo mWifiInfo;
    private int mConfigId = -1;
    private ValueAnimator mProgressAnim;

    private Runnable mFailTask = new Runnable() {
        @Override
        public void run() {
//            WiFiConnectReceiver.removeRegisterObserver(connectObserver);
            if (mConfigId != -1) {
                WifiManager manager = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                manager.removeNetwork(mConfigId);
            }
            WifiListUtils.getInstance().updateWifiList();
            if (mCallBack != null && !mCalledCallBack) {
                mCalledCallBack = true;
                mCallBack.onFailed();
            }
            EnterPwdDialog.enterPwd(getContext(), mWifiInfo, true);
            dismiss();
        }
    };

    private Runnable mSuccessTask = new Runnable() {
        @Override
        public void run() {
//            WiFiConnectReceiver.removeRegisterObserver(connectObserver);
            WifiListUtils.getInstance().updateWifiList();
            if (mCallBack != null && !mCalledCallBack) {
                mCalledCallBack = true;
                mCallBack.onSuccess();
            }
            dismiss();
        }
    };

    private boolean mCalledCallBack;
    private ConnectCallBack mCallBack;

    public static void connect(Context context, WifiInfo wifiInfo) {
        WiFiConnectDialog wiFiConnectDialog = new WiFiConnectDialog(context);
        wiFiConnectDialog.setmWifiInfo(wifiInfo);
        wiFiConnectDialog.show();
    }

    public static void connect(Context context, WifiInfo wifiInfo, ConnectCallBack callBack) {
        WiFiConnectDialog wiFiConnectDialog = new WiFiConnectDialog(context);
        wiFiConnectDialog.setmWifiInfo(wifiInfo);
        wiFiConnectDialog.setConnectCallBack(callBack);
        wiFiConnectDialog.show();
    }

    @Override
    public void show() {
        super.show();
        WiFiConnectReceiver.registerObserver(connectObserver);
        mHandler.postDelayed(mFailConnectTask, MAX_CONNECT_TIME);
    }

    public void setConnectCallBack(ConnectCallBack callBack) {
        this.mCallBack = callBack;
    }

    @Override
    public void dismiss() {
        super.dismiss();
        mHandler.removeCallbacks(mFailTask);
        mHandler.removeCallbacks(mFailConnectTask);
        mHandler.removeCallbacksAndMessages(null);
        if (mProgressAnim != null && mProgressAnim.isRunning()) {
            mProgressAnim.cancel();
        }
    }

    public WiFiConnectDialog(final Context context) {
        super(context);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉title，在有的手机dialog顶部会出现空白
        setContentView(R.layout.app_wifi_connect_dialog);
        ButterKnife.bind(this);
        // 设置弹出窗体的宽和高
        setCanceledOnTouchOutside(false);
        setCancelable(false);
        Window window = getWindow();
        window.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        int index = new Random().nextInt(5);
        if (index == 0) {
            mGifIv.setImageResource(R.drawable.app_wifi_connect_indicator_1);
        } else if (index == 1) {
            mGifIv.setImageResource(R.drawable.app_wifi_connect_indicator_2);
        } else if (index == 2) {
            mGifIv.setImageResource(R.drawable.app_wifi_connect_indicator_3);
        } else if (index == 3) {
            mGifIv.setImageResource(R.drawable.app_wifi_connect_indicator_4);
        } else {
            mGifIv.setImageResource(R.drawable.app_wifi_connect_indicator_5);
        }
        onInit(mWifiInfo);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                onCheck(mWifiInfo);
            }
        }, 1000);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                onConnect(mWifiInfo);
            }
        }, 2000);
        mProgressAnim = ValueAnimator.ofInt(0, 100).setDuration(MAX_CONNECT_TIME);
        mProgressAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                mPbProgress.setProgress((Integer) valueAnimator.getAnimatedValue());
            }
        });
        mProgressAnim.start();
    }

    public void setmWifiInfo(WifiInfo mWifiInfo) {
        this.mWifiInfo = mWifiInfo;
        mTvSsid.setText(WifiUtil.formatSSID(mWifiInfo.getSsid()));
    }

    private void connenctWifi(WifiInfo wifiInfo) {
        try {
            //关闭wifi
            if (wifiInfo != null) {
                if (wifiInfo.isConfig() && wifiInfo.getWifiConfiguration() != null && wifiInfo.getWifiConfiguration().networkId > 0) {
                    WifiUtil.connectToConfiguredNetwork(wifiInfo.getWifiConfiguration().networkId);
                } else {
                    WifiUtil.disableAllWifiConfig();
                    WifiManager manager = (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                    int id = -1;
                    int type = WifiUtil.getLockIntType(wifiInfo.getScanResult().capabilities);
                    final WifiConfiguration config = WifiUtil.CreateWifiInfo(manager, wifiInfo.getSsid()
                            , wifiInfo.getPwd(), type);
                    try {
                        id = manager.addNetwork(config);
                    } catch (Exception var12) {
                    }
                    if (id != -1) {
                        //设置priority
                        int max_pri = WifiUtil.getMaxPriority(manager);
                        max_pri = max_pri < 99999 ? max_pri + 1 : 99999;
                        config.priority = max_pri;
                        manager.updateNetwork(config);
                        mConfigId = id;
                        boolean isConnect = WifiUtil.connectToConfiguredNetwork(id);
                    } else {
                    }
                }
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void onInit(WifiInfo wifiInfo) {
        mIvInit.setImageResource(R.drawable.app_wifi_connect_checking);
        mIvInit.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.anim_check_rotate));
        mIvCheck.setImageResource(R.drawable.app_wifi_connect_checking);
        mIvCheck.setWillNotDraw(true);
        mIvConnect.setImageResource(R.drawable.app_wifi_connect_checking);
        mIvConnect.setWillNotDraw(true);
    }

    @Override
    public void onCheck(WifiInfo wifiInfo) {
        mIvInit.clearAnimation();
        mIvInit.setImageResource(R.drawable.app_wifi_connect_check_ok);
        mIvCheck.setWillNotDraw(false);
        mIvCheck.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.anim_check_rotate));
    }

    @Override
    public void onConnect(WifiInfo wifiInfo) {
        mIvCheck.clearAnimation();
        mIvCheck.setImageResource(R.drawable.app_wifi_connect_check_ok);
        mIvConnect.setWillNotDraw(false);
        mIvConnect.startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.anim_check_rotate));
        connenctWifi(mWifiInfo);
    }

    @Override
    public void onFial(WifiInfo wifiInfo) {
        mHandler.removeCallbacks(mSuccessTask);
        mHandler.removeCallbacks(mFailTask);
        mHandler.postDelayed(mFailTask, 500);
    }

    @Override
    public void onSuccess(WifiInfo wifiInfo) {
        mIvConnect.clearAnimation();
        mIvConnect.setImageResource(R.drawable.app_wifi_connect_check_ok);
        mHandler.removeCallbacks(mFailTask);
        mHandler.removeCallbacks(mSuccessTask);
        mHandler.postDelayed(mSuccessTask, 500);
    }


    private class ConnectObserver extends SimpleConnectChangeObserver {
        @Override
        public void onStateCONNECTED(NetworkInfo wifiInfo, String ssid) {
            if (mWifiInfo != null &&
                    ((wifiInfo != null && WifiUtil.formatSSID(wifiInfo.getExtraInfo()).equals(mWifiInfo.getSsid())) ||
                            (ssid != null && ssid.equals(mWifiInfo.getSsid())))) {
                onSuccess(mWifiInfo);
            }
        }
    }

    public interface ConnectCallBack {
        void onSuccess();

        void onFailed();
    }
}
